//
//  BCAdsManager.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/26.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCAdsManager.h"

@interface BCAdsManager ()

@property (nonatomic, copy) NSString *adsDataPath;


/**
 *adsResponse
 */
@property (nonatomic, strong) BCAdsResponse *adsResponse;

@end

@implementation BCAdsManager

static BCAdsManager *_adsManager = nil;
+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!_adsManager) {
            _adsManager = [[BCAdsManager alloc] init];
        }
    });
    return _adsManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.adsDataPath = [self createCachaAdsFile];
        //取出数据
        [self initLoadData];
    }
    return self;
}
/**
 创建存放广告信息的文件
 */
- (NSString *)createCachaAdsFile {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, true);
    NSString *documentPath = paths[0];
    //创建目录
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *directoryFileName = @"F3APP";
    NSString *directoryPath = [documentPath stringByAppendingPathComponent:directoryFileName];
    if (![fm fileExistsAtPath:directoryPath]) {
        [fm createDirectoryAtPath:directoryPath withIntermediateDirectories:false attributes:nil error:nil];
    }
    //创建文件
    NSString *adsFileName = @"adsData";
    NSString *directoryAds = [directoryPath stringByAppendingPathComponent:adsFileName];
    if (![fm fileExistsAtPath:directoryAds]) {
        [fm createFileAtPath:directoryAds contents:nil attributes:nil];
    }else {
        NSLog(@"已经创建!!!");
    }
    return directoryAds;
}
/**
 初始化时历史数据解析是否有符合规定的启动广告
 */
- (void)initLoadData {
    NSData *responseData = [NSData dataWithContentsOfFile:self.adsDataPath];
    if (responseData.length) {
        BCAdsResponse *response = [BCAdsResponse yy_modelWithJSON:responseData];
        self.adsResponse = response;
        if (response) {
            if (response.data) {
                BCAdsData *adData = response.data;
                if (adData.start.count) {
                    NSArray *start = adData.start;
                    NSMutableArray *reals = [NSMutableArray array];
                    for (int i=0; i<start.count; i++) {
                        BCAdsDataModel *adModel = start[i];
                        //判断adModel是否符合要求 在有效时间之内
                        NSDate *startDate = [NSDate stringToDate:adModel.start_time format:FullDateFormateString];
                        NSDate *endDate = [NSDate stringToDate:adModel.end_time format:FullDateFormateString];
                        NSDate *current = [NSDate date];
                        if ([endDate isLaterThanDate:current]&&[current isLaterThanDate:startDate]) {
                            [reals addObject:adModel];
                        }
                    }
                    //
                    if (reals.count) {
                        NSInteger randomIdx = random()%reals.count;
                        if (randomIdx<reals.count) {
                            BCAdsDataModel *adModel = reals[randomIdx];
                            _launchAdModel = adModel;
                        }
                    }
                }
            }
        }
    }
}

/**
 请求广告数据
 */
- (void)requestAdsData {
    BCAdsRequest *request = [BCAdsRequest new];
    WEAK_SELF
    [request didRequestSuccessed:^(id result, id page) {
        BCAdsResponse *resp = result;
        [wself handleAdsData:resp];
    }];
    [request didRequestFailed:^(NSError *error) {
        
    }];
    [request requestServer];
}

- (void)handleAdsData:(BCAdsResponse *)resp {
    if (resp) {
        self.adsResponse = resp;
        //写入文件
        NSData *respData = [resp yy_modelToJSONData];
        WEAK_SELF
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [respData writeToFile:wself.adsDataPath atomically:true];
        });
        //预下载启动广告图片
        [self preLoadStartImageFromResponse:resp];
    }
}

//
/**
 根据请求相应数据 预先下载启动广告图片 以免下次启动时体验效果不佳的状况
 */
- (void)preLoadStartImageFromResponse:(BCAdsResponse *)resp {
    if (resp) {
        BCAdsData *adData = resp.data;
        if (adData) {
            NSInteger startCount = adData.start.count;
            for (int i=0; i<startCount; i++) {
                BCAdsDataModel *model = adData.start[i];
                [self preLoadStartImageFromAdModel:model];
            }
        }
    }
}
- (void)preLoadStartImageFromAdModel:(BCAdsDataModel *)adModel {
    NSString *imageUrl = adModel.image_url;
    //
    UIImage *adImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:imageUrl];
    if (!adImage) {//反正下载一次不管成功与否
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageDownloaderLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            if (image) {
                [[SDImageCache sharedImageCache] storeImage:image forKey:imageUrl completion:nil];
            }
        }];
    }
}


- (NSArray *)homeAds {
    NSMutableArray *ads = [NSMutableArray array];
    if (self.adsResponse) {
        NSArray *homeAds = self.adsResponse.data.home;
        if (homeAds.count) {
            for (int i=0; i<homeAds.count; i++) {
                BCAdsDataModel *adModel = homeAds[i];
                //判断adModel是否符合要求 在有效时间之内
                NSDate *startDate = [NSDate stringToDate:adModel.start_time format:FullDateFormateString];
                NSDate *endDate = [NSDate stringToDate:adModel.end_time format:FullDateFormateString];
                NSDate *current = [NSDate date];
                if ([endDate isLaterThanDate:current]&&[current isLaterThanDate:startDate]) {
                    [ads addObject:adModel];
                }
            }
        }
    }
    return ads;
}

@end
